"""
Edge TTS实现类
基于edge-tts的TTS实现
"""

import asyncio
import uuid
from typing import Tuple, Dict, Any

import edge_tts

# 导入TTS实现基类
from .base import TTSImplementation
# 导入返回码枚举
from ...constants.return_codes import BaseCodeEnum, ReturnCode
# 导入日志工具
from ...utils.logger import get_logger


class EdgeTTSImplementation(TTSImplementation):
    """
    基于edge-tts的TTS实现
    """

    # 支持的音色列表
    SUPPORTED_VOICES = {
        "zh-CN-XiaoxiaoNeural": "zh-CN-XiaoxiaoNeural",
        "zh-CN-YunyangNeural": "zh-CN-YunyangNeural",
        "zh-CN-XiaohanNeural": "zh-CN-XiaohanNeural",
        "zh-CN-XiaomoNeural": "zh-CN-XiaomoNeural",
        "zh-CN-XiaoxuanNeural": "zh-CN-XiaoxuanNeural",
        "zh-CN-XiaoruiNeural": "zh-CN-XiaoruiNeural",
    }

    # 默认音色
    DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"

    def __init__(self):
        """
        初始化Edge TTS实现
        """
        # 初始化日志记录器
        self.logger = get_logger(__name__)
        pass

    def text_to_speech(self, text: str, voice: str = None, **kwargs) -> Tuple[BaseCodeEnum, Dict[str, Any]]:
        """
        使用edge-tts将文本转换为语音
        
        Args:
            text: 要转换的文本内容
            voice: 音色标识
            **kwargs: 扩展参数，支持output_dir指定输出目录
            
        Returns:
            Tuple[int, str, Dict[str, Any]]: (状态码, 音频文件路径, 结果信息)
        """
        self.logger.info(f"开始文本转语音: text='{text}', voice={voice}")

        # 确定使用的音色
        if voice and voice in self.SUPPORTED_VOICES:
            selected_voice = self.SUPPORTED_VOICES[voice]
        else:
            selected_voice = self.DEFAULT_VOICE

        try:
            # 生成音频文件名
            audio_filename = f"tts_{uuid.uuid4().hex}.mp3"
            # 获取输出目录
            output_dir = kwargs.get('output_dir')
            if output_dir:
                audio_file = f"{output_dir}/{audio_filename}"
            else:
                audio_file = audio_filename

            self.logger.info(f"使用音色: {selected_voice}, 输出文件: {audio_file}")
            # 使用edge-tts进行文本转语音
            communicate = edge_tts.Communicate(text, selected_voice)

            async def _run_with_timeout():
                await communicate.save(audio_file)

            # 创建事件循环并运行异步任务，支持超时
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            try:
                # 获取超时设置
                timeout = kwargs.get('timeout')
                if timeout is not None:
                    loop.run_until_complete(asyncio.wait_for(_run_with_timeout(), timeout=timeout))
                else:
                    loop.run_until_complete(_run_with_timeout())
            finally:
                loop.close()

            self.logger.info(f"TTS转换完成: {audio_file}")

            # 返回成功结果
            result = {
                "text": text,
                "voice": voice or "default",
                "selected_voice": selected_voice,
                "audio_file": audio_file
            }

            return ReturnCode.SUCCESS, result

        except Exception as e:
            # 提供更详细的错误信息
            error_msg = f"TTS转换失败: {str(e)}"
            if "403" in str(e):
                error_msg += " (可能是网络连接问题)"
            self.logger.error(error_msg)
            raise e

    def get_supported_voices(self) -> Dict[str, str]:
        """
        获取支持的音色列表
        
        Returns:
            Dict[str, str]: 音色标识到音色名称的映射
        """
        # 返回支持音色的副本
        return self.SUPPORTED_VOICES.copy()
